package com.aurora.oa.mycenter.view;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputEditText;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.aurora.oa.R;
import com.aurora.oa.activity.BaseActivity;
import com.aurora.oa.bean.HttpResult;
import com.aurora.oa.customview.ItemDivider;
import com.aurora.oa.customview.SelectPicPopupWindow;
import com.aurora.oa.listener.OnSendLogListener;
import com.aurora.oa.listener.OnUploadAttachmentListener;
import com.aurora.oa.listener.OnUploadFeedbackListener;
import com.aurora.oa.message.adapter.ImageSelectAdapter;
import com.aurora.oa.message.bean.ResponseFileID;
import com.aurora.oa.model.RequestHttpModel;
import com.aurora.oa.model.RequestHttpModelImpl;
import com.aurora.oa.utils.StringUtils;
import com.aurora.oa.utils.ToastUtil;
import com.aurora.oa.utils.UriUtils;
import com.aurora.oa.work.bean.SendPatrollogBean;
import com.aurora.oa.work.presenter.WritePatrollogActivityPresenter;
import com.aurora.oa.work.presenter.WritePatrollogActivityPresenterImpl;
import com.aurora.oa.work.view.WritePatrollogActivityView;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/5/5 0005.
 */
public class OptionFeedbackActivity extends BaseActivity {
    @Bind(R.id.et_my_option)
    EditText etMyOption;
    @Bind(R.id.rv_send_imgs)
    RecyclerView rvSendImgs;
    @Bind(R.id.bt_submit)
    Button btSubmit;
    private static final int TAKE_PHOTO = 1;
    private static final int PICK_PHOTO = 2;
    private List<Uri> imageUri = new ArrayList<>();
    //文件上传成功服务器返回
    private List<String> uploadFileIDs = new ArrayList<>();
    List<File> files;
    //自定义的弹出框类
    private SelectPicPopupWindow menuWindow;
    private ProgressDialog progressDialog;
    private ImageSelectAdapter imageSelectAdapter;
    RequestHttpModel model = new RequestHttpModelImpl();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setMyContentView(R.layout.activity_option_feedback);
        ButterKnife.bind(this);
        initData();
    }

    @OnClick(R.id.bt_submit)
    public void onClick() {
        sendData();
    }

    private void sendData() {
        final String title = "";
        final String content = etMyOption.getText().toString();
        String attachmentids = StringUtils.getStringFromList(uploadFileIDs);
        if(imageUri.size()==0){
            model.doSendFeedback(title,content,attachmentids, new OnUploadFeedbackListener() {
                @Override
                public void onUploadFeedbackSuccess() {
                    ToastUtil.show(getApplicationContext(),"意见上传成功");
                    finish();
                }

                @Override
                public void onUploadFeedbackFail(String message) {
                    ToastUtil.show(getApplicationContext(),message);
                }
            });
        }else{
            files = getImageFiles();
            for(int i = 0 ;i<files.size();i++){
                model.uploadAttachment(files.get(i), new OnUploadAttachmentListener() {
                    @Override
                    public void onUploadAttachmentSuccess(ResponseFileID attachId) {
                        uploadFileIDs.add(attachId.getMsg());
                        //所有图片上传完成
                        if(uploadFileIDs.size()==files.size()){
                            //开始上传数据
                            String attachmentids = StringUtils.getStringFromList(uploadFileIDs);

                            model.doSendFeedback(title,content,attachmentids, new OnUploadFeedbackListener() {
                                @Override
                                public void onUploadFeedbackSuccess() {
                                    ToastUtil.show(getApplicationContext(),"意见上传成功");
                                    finish();
                                }

                                @Override
                                public void onUploadFeedbackFail(String message) {
                                    ToastUtil.show(getApplicationContext(),message);
                                }
                            });
                        }

                    }

                    @Override
                    public void onUploadAttachmentFail(String message) {
                        ToastUtil.show(getApplicationContext(),message);
                    }
                });
            }
        }


    }

    private void initData() {
        imageSelectAdapter = new ImageSelectAdapter(this, imageUri);
        imageSelectAdapter.setOnItemClickListener(new ImageSelectAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (position == imageUri.size()) {
                    //选择图片
                    //实例化SelectPicPopupWindow
                    menuWindow = new SelectPicPopupWindow(OptionFeedbackActivity.this, itemsOnClick);
                    //显示窗口
                    menuWindow.showAtLocation(null, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
                }
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });
        rvSendImgs.setAdapter(imageSelectAdapter);
        rvSendImgs.setLayoutManager(new GridLayoutManager(this, 3));
        rvSendImgs.setItemAnimator(new DefaultItemAnimator());
        rvSendImgs.addItemDecoration(new ItemDivider().setDividerWith(3).setDividerColor(Color.TRANSPARENT));

    }

    //为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.btn_take_photo:
                    Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(it, TAKE_PHOTO);
                    break;
                case R.id.btn_pick_photo:
                    Intent local = new Intent();
                    local.setType("image/*");
                    local.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(local, PICK_PHOTO);
                    break;
                default:
                    break;
            }
        }
    };

    public List<File> getImageFiles() {
        List<File> files = new ArrayList<>();
        for (Uri uri : imageUri) {
            files.add(new File(UriUtils.getRealFilePath(this, uri)));
        }
        return files;
    }
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case TAKE_PHOTO:
                    Bundle extras = data.getExtras();
                    Bitmap b = (Bitmap) extras.get("data");
                    String name = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
                    String fileNmae = Environment.getExternalStorageDirectory().toString() + File.separator + "aurora/image/" + name + ".jpg";
                    String srcPath = fileNmae;
                    File myCaptureFile = new File(fileNmae);
                    try {
                        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                            if (!myCaptureFile.getParentFile().exists()) {
                                myCaptureFile.getParentFile().mkdirs();
                            }
                            BufferedOutputStream bos;
                            bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
                            b.compress(Bitmap.CompressFormat.JPEG, 80, bos);
                            bos.flush();
                            bos.close();
                            Uri uri = Uri.fromFile(myCaptureFile);
                            imageUri.add(uri);
                            imageSelectAdapter.notifyDataSetChanged();
                            imageSelectAdapter.notifyItemRemoved(imageSelectAdapter.getItemCount());

                        } else {

                            Toast toast = Toast.makeText(OptionFeedbackActivity.this, "保存失败，SD卡无效", Toast.LENGTH_SHORT);
                            toast.show();
                        }
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
                case PICK_PHOTO:
                    Uri uri = data.getData();
                    imageUri.add(uri);
                    imageSelectAdapter.notifyDataSetChanged();
                    imageSelectAdapter.notifyItemRemoved(imageSelectAdapter.getItemCount());
                    break;
                default:
                    break;
            }
            ;
        }
    }
}



